using Microsoft.Extensions.Logging;
using AgentFrameworkDemo.Models;
using AgentFrameworkDemo.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AgentFrameworkDemo;

/// <summary>
/// 诗词快速演示 - 展示Microsoft风格Agent工具的简洁性
/// </summary>
public class PoetryQuickDemo
{
    public static async Task RunAsync(string[] args)
    {
        Console.WriteLine("📜 Microsoft风格Agent工具演示");
        Console.WriteLine("诗词分析：问君能有几多愁");
        Console.WriteLine("=====================================");

        // 创建服务容器
        var services = new ServiceCollection();
        services.AddLogging(builder => builder.AddConsole());
        services.AddSingleton<IAgentManager, AgentManager>();
        services.AddSingleton<IMemoryManager, MemoryManager>();
        services.AddSingleton<IToolManager, ToolManager>();
        services.AddSingleton<ISystemPromptService, SystemPromptService>();
        // AgentFunctionTool 是静态类，无需注册

        var serviceProvider = services.BuildServiceProvider();

        // 初始化Microsoft风格工具
        AgentFunctionTool.Initialize(serviceProvider);

        try
        {
            // 获取服务
            var agentManager = serviceProvider.GetRequiredService<IAgentManager>();
            var logger = serviceProvider.GetRequiredService<ILogger<PoetryQuickDemo>>();

            Console.WriteLine("\n🎯 创建诗词专家Agent...");

            // 创建诗词专家Agent
            var poetryAgentDefinition = new AgentDefinition
            {
                Name = "诗词专家",
                Description = "精通中国古典诗词的AI专家",
                Tags = ["tool", "poetry", "literature"],
                Capabilities = new AgentCapabilities
                {
                    EnableMemory = true,
                    EnableTools = false
                },
                Configuration = new AgentConfiguration
                {
                    Model = new AIModelConfig
                    {
                        Provider = "ZhipuAI",
                        ModelId = "glm-4.5",
                        ApiKey = "08ffd1f87b0e4914be6542b892d327cd.QKnNO0dKRUljxxXv",
                        Endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions",
                        Temperature = 0.8,
                        MaxTokens = 300
                    }
                }
            };

            var poetryAgent = await agentManager.CreateAgentAsync(poetryAgentDefinition);
            Console.WriteLine($"✅ 诗词专家创建成功: {poetryAgent.Id}");

            // Microsoft风格：转换为AI函数（1行代码）
            Console.WriteLine("\n🔄 Microsoft风格转换 - agent.AsAIFunction()");
            var poetryFunction = poetryAgent.AsAIFunction("poetry_expert", "诗词分析专家");
            Console.WriteLine($"✅ 转换成功: {poetryFunction.Name}");

            // 执行诗词分析（1行代码）
            Console.WriteLine("\n📝 分析经典诗词：'问君能有几多愁'");
            var result = await poetryFunction.InvokeWithStringInputAsync("请分析李煜的词句'问君能有几多愁，恰似一江春水向东流'的意境和情感表达");

            // 展示结果
            Console.WriteLine("\n🎨 诗词分析结果:");
            if (result is Dictionary<string, object> dict)
            {
                var content = dict.GetValueOrDefault("content")?.ToString() ?? "无内容";
                var success = dict.GetValueOrDefault("success")?.ToString();

                Console.WriteLine($"✅ 执行状态: {success}");
                Console.WriteLine($"📖 分析内容:");
                Console.WriteLine("----------------------------------------");
                Console.WriteLine(content);
                Console.WriteLine("----------------------------------------");

                // 显示企业级特性
                if (dict.TryGetValue("enterprise", out var enterpriseInfo) &&
                    enterpriseInfo is Dictionary<string, object> enterprise)
                {
                    Console.WriteLine("\n🏢 企业级特性:");
                    Console.WriteLine($"📊 审计ID: {enterprise.GetValueOrDefault("audit_log_id")}");
                }
            }

            // 展示API简洁性
            Console.WriteLine("\n📊 API简洁性对比:");
            Console.WriteLine("❌ 旧方式（复杂）:");
            Console.WriteLine("   await agentToolExecutor.RefreshAgentToolsAsync();");
            Console.WriteLine("   var tools = await agentToolExecutor.GetAvailableToolsAsync();");
            Console.WriteLine("   var request = new ToolExecutionRequest { /* 复杂配置 */ };");
            Console.WriteLine("   var result = await agentToolExecutor.ExecuteToolAsync(request);");

            Console.WriteLine("\n✅ 新方式（Microsoft风格）:");
            Console.WriteLine("   var func = agent.AsAIFunction(\"poetry_expert\");");
            Console.WriteLine("   var result = await func.InvokeWithStringInputAsync(\"分析请求\");");
            Console.WriteLine("   // 总共2行代码！");

            Console.WriteLine("\n🎉 诗词演示完成！");
            Console.WriteLine("Microsoft风格Agent工具：简洁、优雅、强大");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"\n❌ 演示失败: {ex.Message}");
            Console.WriteLine("请检查API密钥和网络连接");
        }

        Console.WriteLine("\n按Enter键退出...");
        try
        {
            Console.ReadLine();
        }
        catch (InvalidOperationException)
        {
            // 在没有控制台的情况下忽略异常
        }
    }
}